package org.ccay.message.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.IUserPrincipal;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.util.JsonUtil;
import org.ccay.core.util.StringUtil;
import org.ccay.message.PushMessageApplicationException;
import org.ccay.message.PushMessageVO;
import org.ccay.message.service.IPushMessageService;
import org.ccay.registry.util.RegistryQueryUtil;

/**
 * 
 * 消息推送处理器实现
 * 
 * @author chaowangbang
 * @since 2012-12-3
 */
@Named
public class PushMessageProcesser implements IMessageProcessor {
	/** 日志记录器 **/
	private final ILogger logger = CcayLoggerFactory.getLogger(PushMessageProcesser.class);

	private static final String ICO = "Ico";
//	private static final String ENABLED = "Enabled";
	private static final String STYLE = "Style";
	private static final String EXPIRESMINUTES = "ExpiresMinutes";
	private static final String TEMPLATE = "Template";
	private static final String LEVEL = "Level";
	
	private static final int MESSAGEOVERDUE = 180000; 
	
	/**
	 * TRUE 的字符串表示形式（1）
	 */
	public static final String CODE_TURE = "1";

	@Inject
	private IPushMessageService pushMessageService;

	
	/**
	 * 邮件模板
	 */
//	@Inject
//	TODO private ITemplateService templateService;
	
	/*
	 * (non-Javadoc)
	 * @see org.ccay.async.IMessageProcessor#process(org.ccay.async.AsyncMessage)
	 */
	public void process(AsyncMessage message) throws ApplicationException {
		PushMessageVO pushMessageVO = (PushMessageVO) message.getContent();
		Map<String, String> messageParameterMap = null;
		try {
			messageParameterMap = initMessageParameter(pushMessageVO.getMessageType());
		} catch (ApplicationException e) {
			logger.error("The exception occured during initialize "+pushMessageVO.getMessageType()+"'s parameterMap",e);
		}
		createMessage(pushMessageVO,messageParameterMap);
	}
	/**
	 * 创建消息
	 * @param pushMessageVO
	 * @param messageParameterMap
	 * Created：2012-12-8
	 * @author chaowangbang
	 */
	private void createMessage(PushMessageVO pushMessageVO,Map<String, String> messageParameterMap){

		try {
			pushMessageVO.setMessageIco(messageParameterMap.get(ICO));
			pushMessageVO.setMessageStyle(messageParameterMap.get(STYLE));
			pushMessageVO.setMessageTemplate(messageParameterMap.get(TEMPLATE));
			pushMessageVO.setMessageLevel(Integer.valueOf(messageParameterMap.get(LEVEL)));
			if(StringUtil.isNullOrEmpty(pushMessageVO.getMessageReceiver())){
				//获取当前用户
				IUserPrincipal user =  RequestContext.getCurrent().getUser();
				if(user == null){
					logger.warn(pushMessageVO.getMessageType()+"'s receiver is null ");
					throw new PushMessageApplicationException("ccay.pushMessage.00010004");
				}
				pushMessageVO.setMessageReceiver(String.valueOf(user.getUserId()));
			}
			//TODO setTemplateData(pushMessageVO);
			//setTemplateData(pushMessageVO);
			long  newDate = new Date().getTime();
			long  expiresMinutes = (messageParameterMap.get(EXPIRESMINUTES)==null? MESSAGEOVERDUE : Integer.parseInt(messageParameterMap.get(EXPIRESMINUTES))*60000L);
			pushMessageVO.setMessageOverdue(new Date(newDate+ expiresMinutes));
			pushMessageService.createMessage(pushMessageVO);
		} catch (ApplicationException ex) {
			logger.error(ex);
		}
	}
//	private void setTemplateData(PushMessageVO pushMessageVO) throws ApplicationException{
//		TemplateUtil.putAppRoot(pushMessageVO.getBindItems());
//		// 调用mailTemplateService进行查找富文本，得到模板template
//		TemplateVO template = templateService.findTemplate("MessageTemplate",pushMessageVO.getMessageTemplate());		 
//		try {
//			//获取内容
//			String finalContent=TemplateUtil.putDataIntoTemplate(template.getTemplateContent(), pushMessageVO.getBindItems());
//			//获取主题
//			String finalSubject=TemplateUtil.putDataIntoTemplate(template.getTemplateTitle(), pushMessageVO.getBindItems());
//			//设置内容
//			pushMessageVO.setMessageTemplate(finalContent);
//			//设置主题
//			pushMessageVO.setMessageTitle(finalSubject);
//		} catch (TemplateException e) {
//			// TemplateException
//			throw new PushMessageApplicationException("ccay.pushMessage.00010003", e);
//		}catch (IOException e) {
//			throw new PushMessageApplicationException("ccay.pushMessage.00010002", e);
//		}catch (RuntimeException e) {
//			// TemplateException
//			throw new PushMessageApplicationException("ccay.pushMessage.00010003", e);
//		} 
//	}
	/**
	 * 根据消息类从数据字典获取该消息类型下的配置选项集合
	 * 
	 * @author chaowangbang
	 * @since 2012-12-3
	 * @param messageType
	 * @throws ApplicationException 
	 */
	@SuppressWarnings("unchecked")
	private Map<String, String> initMessageParameter(String messageType) throws ApplicationException {
		String messageTypePath = "App.PushMessage." + messageType;
		String value = RegistryQueryUtil.getValue(messageTypePath);
		if(StringUtils.isEmpty(value)){
			throw new PushMessageApplicationException("ccay.pushMessage.00010001",messageType);
		}
		Map<String, String> messageParameterMap;
		try {
			messageParameterMap = JsonUtil.stringToObject(value, Map.class);
		} catch (IOException e) {
			throw new PushMessageApplicationException("ccay.pushMessage.00010006",messageType);
		}
		return messageParameterMap;
	}
}
